<?php
// 配置参数
$api_url = "https://ark.cn-beijing.volces.com/api/v3/images/generations";
$save_dir = getenv('BOZO') . "/Downloads/";
$api_key = getenv('ARK_API_KEY');

// 确保保存目录存在
if (!is_dir($save_dir)) {
    mkdir($save_dir, 0755, true);
}

// 尺寸映射
// $size_mapping = [
//     "9:16（竖屏）" => "1152x2048",
//     "16:9（横屏）" => "2048x1152",
//     "1:1（正方形）" => "1536x1536",
//     "4:3（传统显示器）" => "1772x1329",
//     "3:4（竖向4:3）" => "1329x1772",
//     "2:3（宽屏）" => "2352x1008",
//     "3:2（35mm胶片）" => "1881x1254",
//     "21:9（超宽屏）" => "2352x1008",
// ];

$size_mapping = [
    "9:16（竖屏）" => "1536x2730",
    "16:9（横屏）" => "2730x1536",
    "1:1（正方形）" => "2048x2048",
    "4:3（传统显示器）" => "2300x1800",
    "3:4（竖向4:3）" => "1800x2300",
    "2:3（宽屏）" => "1600x2400",
    "3:2（35mm胶片）" => "2400x1600",
    "21:9（超宽屏）" => "2830x1480",
];

// 初始化变量
$prompt = "";
$size_option = "1:1（正方形）";
$image_url = "";
$status = "";
$generated_image = "";

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prompt = $_POST['prompt'] ?? '';
    $size_option = $_POST['size'] ?? '1:1（正方形）';
    
    if (empty($prompt)) {
        $status = "请输入提示词";
    } elseif (empty($api_key)) {
        $status = "API密钥未配置";
    } else {
        try {
            $start_time = microtime(true);
            
            // 准备请求数据
            $selected_size = $size_mapping[$size_option];
            $post_data = [
                "model" => "doubao-seedream-3-0-t2i-250415",
                "prompt" => $prompt,
                "response_format" => "url",
                "size" => $selected_size,
                "seed" => -1,
                "guidance_scale" => 2.5,
                "watermark" => false
            ];
            
            // 发送API请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Content-Type: application/json",
                "Authorization: Bearer " . $api_key
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code == 200) {
                $response_data = json_decode($response, true);
                $image_url = $response_data["data"][0]["url"];
                
                // 下载并保存图片
                $timestamp = date("Ymd_His");
                $filename = "豆包_{$timestamp}.jpeg";
                $save_path = $save_dir . $filename;
                
                // 下载图片
                file_put_contents($save_path, file_get_contents($image_url));
                
                $end_time = microtime(true);
                $status = "图片生成成功！耗时: " . number_format($end_time - $start_time, 2) . " 秒";
                $generated_image = $image_url;
            } else {
                $status = "请求失败，状态码：{$http_code}，错误信息：{$response}";
            }
        } catch (Exception $e) {
            $status = "生成失败，错误信息：" . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>豆包图片生成器 | AI创意工坊</title>
    <!-- 外部资源 -->
    <link href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.staticfile.net/motion.js/0.3.0/motion.min.js"></script>
    
    <script>
        // 深色模式检测与设置
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
        
        // 图片下载功能
        function downloadImage() {
            const imgSrc = document.getElementById('generated-image')?.src;
            if (!imgSrc) {
                alert('没有可下载的图片');
                return;
            }
            
            const a = document.createElement('a');
            a.href = imgSrc;
            a.download = '豆包生成图片_' + new Date().getTime() + '.jpg';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
        }
    </style>
    
    <style>
        /* 基础样式 */
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
        }
        
        .noto-serif {
            font-family: 'Noto Serif SC', serif;
        }
        
        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
    </style>
</head>

<!-- 深色/浅色模式类 -->
<body class="bg-gray-50 text-gray-900 dark:bg-gray-900 dark:text-gray-100 transition-custom min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="sticky top-0 z-50 bg-white/80 dark:bg-gray-900/80 backdrop-blur-md shadow-sm transition-custom">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fas fa-magic text-indigo-600 dark:text-indigo-400 text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold noto-serif">豆包图片生成器</h1>
            </div>
            
            <!-- 模式切换按钮 -->
            <button id="theme-toggle" class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-custom">
                <i class="fas dark:hidden fa-moon text-gray-700"></i>
                <i class="fas hidden dark:inline fa-sun text-yellow-400"></i>
            </button>
        </div>
    </header>

    <!-- Hero 模块 -->
    <section class="bg-gradient-to-r from-indigo-600 to-purple-600 dark:from-indigo-800 dark:to-purple-800 text-white py-12 md:py-20">
        <div class="container mx-auto px-4 text-center">
            <h2 class="text-3xl md:text-5xl font-bold mb-4 noto-serif text-shadow">用文字创造视觉艺术</h2>
            <p class="text-lg md:text-xl max-w-2xl mx-auto opacity-90">只需输入描述，AI就能为您生成精美的图片，释放您的创造力</p>
        </div>
    </section>

    <!-- 主要内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8 md:py-12">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 输入区域 -->
            <div class="lg:col-span-1">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 transition-custom hover:shadow-lg">
                    <h3 class="text-xl font-semibold mb-6 flex items-center">
                        <i class="fas fa-pen-to-square text-indigo-500 mr-2"></i>
                        生成设置
                    </h3>
                    
                    <form method="post" class="space-y-5">
                        <div>
                            <label for="prompt" class="block text-sm font-medium mb-2">提示词</label>
                            <textarea 
                                id="prompt" 
                                name="prompt" 
                                placeholder="请输入详细的中文描述，例如：一片宁静的湖泊，周围环绕着雪山，蓝天白云，风格类似于印象派绘画..."
                                class="w-full p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-custom resize-none h-32"
                            ><?php echo htmlspecialchars($prompt); ?></textarea>
                            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">提示词越详细，生成效果越符合预期</p>
                        </div>
                        
                        <div>
                            <label for="size" class="block text-sm font-medium mb-2">图片尺寸</label>
                            <select 
                                id="size" 
                                name="size" 
                                class="w-full p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-custom"
                            >
                                <?php foreach ($size_mapping as $key => $value): ?>
                                    <option value="<?php echo htmlspecialchars($key); ?>" 
                                        <?php echo ($size_option == $key) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($key); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <button 
                            type="submit" 
                            class="w-full bg-indigo-600 hover:bg-indigo-700 dark:bg-indigo-700 dark:hover:bg-indigo-800 text-white font-medium py-3 px-4 rounded-lg transition-custom flex items-center justify-center space-x-2"
                        >
                            <i class="fas fa-magic"></i>
                            <span>生成图片</span>
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- 输出区域 -->
            <div class="lg:col-span-2">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 transition-custom hover:shadow-lg h-full">
                    <h3 class="text-xl font-semibold mb-6 flex items-center">
                        <i class="fas fa-image text-indigo-500 mr-2"></i>
                        生成结果
                    </h3>
                    
                    <!-- 图片显示区域 -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium mb-2">生成的图片</label>
                        <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-900 min-h-[300px] flex items-center justify-center">
                            <?php if (!empty($generated_image)): ?>
                                <img 
                                    id="generated-image" 
                                    src="<?php echo htmlspecialchars($generated_image); ?>" 
                                    alt="生成的图片" 
                                    class="max-w-full max-h-[600px] object-contain fade-in"
                                >
                            <?php else: ?>
                                <div class="text-center p-8 text-gray-500 dark:text-gray-400">
                                    <i class="fas fa-picture-o text-5xl mb-4 opacity-30"></i>
                                    <p>等待生成图片...</p>
                                    <p class="text-xs mt-2">点击"生成图片"按钮开始创作</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($generated_image)): ?>
                            <div class="mt-4 flex justify-center">
                                <button 
                                    onclick="downloadImage()"
                                    class="bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-custom flex items-center space-x-2"
                                >
                                    <i class="fas fa-download"></i>
                                    <span>下载图片</span>
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- 状态信息 -->
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">图片URL地址</label>
                            <div class="bg-gray-50 dark:bg-gray-700 p-3 rounded-lg text-sm overflow-x-auto">
                                <?php echo htmlspecialchars($image_url); ?>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium mb-2">状态信息</label>
                            <div class="p-3 rounded-lg border 
                                <?php 
                                    if (strpos($status, '成功') !== false) {
                                        echo 'border-green-200 bg-green-50 dark:border-green-900 dark:bg-green-900/20 text-green-800 dark:text-green-400';
                                    } elseif (!empty($status)) {
                                        echo 'border-red-200 bg-red-50 dark:border-red-900 dark:bg-red-900/20 text-red-800 dark:text-red-400';
                                    } else {
                                        echo 'border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
                                    }
                                ?>
                            ">
                                <?php echo empty($status) ? '准备就绪' : htmlspecialchars($status); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 提示词建议 -->
        <div class="mt-10 bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 transition-custom">
            <h3 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fas fa-lightbulb text-yellow-500 mr-2"></i>
                提示词建议
            </h3>
            <p class="mb-4">以下是一些优秀的提示词示例，您可以参考它们的格式和风格：</p>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                    <p class="text-sm italic">"一只坐在月球上的兔子，望着地球，星空背景，水彩风格，柔和的色调"</p>
                </div>
                <div class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                    <p class="text-sm italic">"未来城市的天际线，飞行器穿梭其间，霓虹灯光，赛博朋克风格，雨天效果"</p>
                </div>
                <div class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                    <p class="text-sm italic">"宁静的日式庭院，樱花飘落，池塘中有锦鲤，传统建筑，春天，阳光明媚"</p>
                </div>
                <div class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                    <p class="text-sm italic">"抽象的几何构图，蓝色和紫色渐变，动态感，极简主义，高对比度"</p>
                </div>
            </div>
        </div>
        
        <!-- 延伸阅读 -->
        <!-- <div class="mt-10 bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 transition-custom">
            <h3 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fas fa-book text-indigo-500 mr-2"></i>
                进一步阅读
            </h3>
            <ul class="space-y-3">
                <li class="flex items-start">
                    <i class="fas fa-angle-right text-indigo-500 mt-1 mr-2"></i>
                    <span>《人工智能艺术创作》- 探讨AI在视觉艺术领域的应用与发展</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-angle-right text-indigo-500 mt-1 mr-2"></i>
                    <span>《提示工程指南》- 学习如何编写更有效的AI提示词</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-angle-right text-indigo-500 mt-1 mr-2"></i>
                    <span>《生成式AI：从概念到实践》- 介绍生成式人工智能的核心技术</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-angle-right text-indigo-500 mt-1 mr-2"></i>
                    <span>《数字艺术设计原理》- 学习如何评估和改进AI生成的视觉作品</span>
                </li>
                <li class="flex items-start">
                    <i class="fas fa-angle-right text-indigo-500 mt-1 mr-2"></i>
                    <span>《创意编程入门》- 探索代码与艺术创作的结合方式</span>
                </li>
            </ul>
        </div> -->
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-100 dark:bg-gray-800 py-8 mt-12">
        <div class="container mx-auto px-4 text-center text-gray-600 dark:text-gray-400 text-sm">
            <p>© <?php echo date('Y'); ?> 豆包图片生成器 | 基于AI技术的创意工具</p>
            <p class="mt-2">使用前请确保您拥有生成内容的合法使用权</p>
        </div>
    </footer>

    <!-- 深色模式切换脚本 -->
    <script>
        // 模式切换功能
        document.getElementById('theme-toggle').addEventListener('click', function() {
            if (document.documentElement.classList.contains('dark')) {
                document.documentElement.classList.remove('dark');
                localStorage.theme = 'light';
            } else {
                document.documentElement.classList.add('dark');
                localStorage.theme = 'dark';
            }
        });
        
        // 表单提交时的加载效果
        document.querySelector('form').addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>生成中...</span>';
            
            // 防止长时间无响应
            setTimeout(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }, 60000);
        });
        
        // 添加滚动动画
        document.addEventListener('DOMContentLoaded', function() {
            const sections = document.querySelectorAll('section, main > div');
            
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('fade-in');
                        observer.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.1 });
            
            sections.forEach(section => {
                observer.observe(section);
            });
        });
    </script>
</body>
</html>
